package com.ruoyi.project.im.code.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.IpToAddressUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.project.im.avatar.domain.VisitorAvatar;
import com.ruoyi.project.im.avatar.service.IVisitorAvatarService;
import com.ruoyi.project.im.bean.IMAuth;
import com.ruoyi.project.im.bean.IMBaseRes;
import com.ruoyi.project.im.code.domain.UserCode;
import com.ruoyi.project.im.users.domain.Users;
import com.ruoyi.project.im.users.service.IUsersService;
import com.ruoyi.project.im.utils.Http;
import com.ruoyi.project.im.utils.IMManager;
import com.ruoyi.project.im.utils.RandomNum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.im.code.domain.Code;
import com.ruoyi.project.im.code.service.ICodeService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 卡密Controller
 * 
 * @author ruoyi
 * @date 2023-02-24
 */
@Controller
@RequestMapping("/im/code")
public class CodeController extends BaseController
{
    private String prefix = "im/code";

    @Autowired
    private ICodeService codeService;

    @Autowired
    private IVisitorAvatarService avatarService;

    @Autowired
    private IUsersService usersService;

    @RequiresPermissions("im:code:view")
    @GetMapping()
    public String code()
    {
        return prefix + "/code";
    }

    /**
     * 查询卡密列表
     */
    @RequiresPermissions("im:code:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Code code)
    {
        startPage();
        List<Code> list = codeService.selectCodeList(code);
        return getDataTable(list);
    }

    /**
     * 导出卡密列表
     */
    @RequiresPermissions("im:code:export")
    @Log(title = "卡密", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Code code)
    {
        List<Code> list = codeService.selectCodeList(code);
        ExcelUtil<Code> util = new ExcelUtil<Code>(Code.class);
        return util.exportExcel(list, "卡密数据");
    }

    private VisitorAvatar getAvatar() {
        VisitorAvatar visitorAvatar = avatarService.selectVisitorAvatarById(0L);
        if (visitorAvatar != null) {
            visitorAvatar.setuCount(visitorAvatar.getuCount() + 1);
            avatarService.updateVisitorAvatar(visitorAvatar);
            return visitorAvatar;
        }
        return null;
    }

    /**
     * 新增卡密
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存卡密
     */
    @RequiresPermissions("im:code:add")
    @Log(title = "卡密", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(UserCode code)
    {
        Integer num=code.getNum();
        String type=code.getKamitype();
        String kwz="";
        if("uselogin".equals(type)){
            kwz="LG";
        }else if("useceshi".equals(type)){
            kwz="CS";
        }else if("usexufei".equals(type)){
            kwz="XF";
        }
        int total=0;
        for (int i = 0; i < num; i++) {
            String kimicode=RandomNum.randomdaxie(10)+"-"+kwz;
            Code code1=new Code();
            code1.setAddtime(new Date());
            code1.setKamicode(kimicode);
            code1.setIssold("sold");
            code1.setKamistatus("nouse");
            code1.setDays(code.getDays());
            code1.setKamitype(type);
            int f= codeService.insertCode(code1);
            if("uselogin".equals(type)||"useceshi".equals(type)){//注册用户
                VisitorAvatar visitorAvatar = getAvatar(); //生成用户
                if (visitorAvatar == null) {
                    return AjaxResult.error("注册 500");
                }
                String nickname = visitorAvatar.getName();
                String userId = UUID.fastUUID().toString();
                String avatar = visitorAvatar.getAvatar();
                Users users = new Users();
                users.setUserId(userId);
                users.setName(nickname);
                users.setFaceUrl(avatar);
                users.setKamicode(kimicode);
                users.setAppMangerLevel(3);
                users.setActStatus(0);
                users.setCreateUser(getSysUser().getLoginName());
                if(registerUser(userId,nickname,avatar)){
                    usersService.updateUsers(users);
                    total += f;
                }else {
                    return AjaxResult.error("注册用户失败");
                }
            }
//            total+=f;
        }
        if(total==num){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }

    }


    private boolean registerUser(String userId,String nickname,String avatar){

        Map<String,Object> map = new HashMap<>();
        map.put("nickname",nickname);
        map.put("faceURL",avatar);
        map.put("platform",5);
        map.put("userID",userId);
        map.put("operationID", IMManager.getOperationID());
        map.put("secret", IMManager.secret);

        String jsonString = JSON.toJSONString(map);
        JSONObject result = Http.post(Http.USER_REGISTER,jsonString);
        IMBaseRes baseRes = result.toJavaObject(IMBaseRes.class);
        JSON json = JSON.parseObject(baseRes.data.toString());
        IMAuth imAuth = json.toJavaObject(IMAuth.class);
        if (!StringUtils.isEmpty(imAuth.token)){
            return true;
        }else {
            return false;
        }

    }

    /**
     * 修改卡密
     */
    @RequiresPermissions("im:code:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Code code = codeService.selectCodeById(id);
        mmap.put("code", code);
        return prefix + "/edit";
    }

    /**
     * 修改保存卡密
     */
    @RequiresPermissions("im:code:edit")
    @Log(title = "卡密", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Code code)
    {
        return toAjax(codeService.updateCode(code));
    }

    /**
     * 修改保存卡密
     */
    @RequiresPermissions("im:code:edit")
    @Log(title = "卡密", businessType = BusinessType.UPDATE)
    @PostMapping("/changeIsSold")
    @ResponseBody
    public AjaxResult changeIsSold(Code code)
    {
        return toAjax(codeService.updateCode(code));
    }

    /**
     * 删除卡密
     */
    @RequiresPermissions("im:code:remove")
    @Log(title = "卡密", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(codeService.deleteCodeByIds(ids));
    }
}
